<template>
  <div class="b-dialog-application__side flex flex-col">
    <div class="b-dialog-application__side-item">
      <span class="b-dialog-application__side-item--name">{{$t('paywall.publisher')}}</span>
      <span class="b-dialog-application__side-item-value">{{name}}</span>
    </div>
    <div class="b-dialog-application__side-item">
      <span class="b-dialog-application__side-item--name">{{$t('paywall.lastUpdated')}}</span>
      <span class="b-dialog-application__side-item--value">{{updated}}</span>
    </div>
    <div class="b-dialog-application__side-item">
      <span class="b-dialog-application__side-item--name">{{$t('paywall.integration')}}</span>
      <BIntegration :options="integrations" />
    </div>
    <div class="b-dialog-application__side-pay">
      <div class="b-dialog-application__side-item b-dialog-application__side-pay-price items-start! ">
        <span class="b-dialog-application__side-item--name">{{$t('paywall.price')}}
          <el-tooltip :open-delay="1000"
                      popper-class="price-tooltip"
                      :content="$t('paywall.tcps')">
            <ZIcon icon="cuifont icon_help_circle"
                   class="help cursor-pointer"
                   color="#000000"
                   :size="12" />
          </el-tooltip>
        </span>
        <div class="b-dialog-application__side-item-price items-end">
          <ZPrice :value="meta.price"
                  effect="primary"
                  v-if="meta.price" />
          <span v-else>Free</span>
          <span class="b-application__header-price--unit  items-end"
                v-if="meta.unit">{{meta.unit}}</span>
          <span class="b-application__header-price--unit  text-right">/{{unit | filterUnitCode}}</span>
        </div>

      </div>
      <el-button type="primary"
                 size="mini"
                 v-if="!isFree && ((type === 1 || type === 3) && !payBundle)"
                 :disabled="getDisabledState()"
                 @click="purchase">
        {{payStateName}}
      </el-button>
      <el-button type="primary"
                 size="mini"
                 v-else-if="!isFree"
                 :disabled="(installed && isPay)|| getDisabledState()"
                 @click="purchase">
        {{payStateName}}
      </el-button>
      <el-button type="primary"
                 size="mini"
                 v-if="isFree && type === 2"
                 :disabled="installed"
                 @click="add">
        {{installed || getDisabledState()?$t('paywall.installed'):$t('paywall.install')}}
      </el-button>
      <el-button type="primary"
                 size="mini"
                 v-if="!installed && (type === 1 ) "
                 style="margin-left:0;margin-top:8px"
                 :disabled="!$hasPermission('sys:marketplace:add')"
                 @click="add">
        Add
      </el-button>
      <el-button type="primary"
                 size="mini"
                 v-if="installed && type === 1"
                 disabled
                 style="margin-left:0;margin-top:8px">
                 Installed
      </el-button>
    </div>
  </div>
</template>

<script>
import BIntegration from '@/components/storybook/b-integration/index'
import ZPrice from '@/components/storybook/z-price'
import ZIcon from '@/components/storybook/z-icon'
import useMeta from '@/components/storybook/hooks/useMeta'
import { capitalize } from 'lodash'

export default {
  name: 'BDialogApplicationSide',
  inject: {
    _tenantCode: {
      default: () => {
        return function () {}
      }
    }
  },
  components: {
    BIntegration,
    ZPrice,
    ZIcon
  },
  props: {
    name: String,
    updated: String,
    integrations: {
      type: Array,
      default: () => ([])
    },

    unit: {
      type: String,
      default: 'month'
    },
    type: [String, Number],
    mode: [String, Number],
    cost: {
      type: Array,
      default: () => ([])
    },
    items: {
      type: Array,
      default: () => ([])
    },
    appId: [String, Number],
    installed: Boolean,
    aliseName: String
  },
  data () {
    return {
      bundleName: '',
      selectBiList: [],
      payHistory: [],
      isPay: false
    }
  },
  watch: {
    appId: {
      handler: function (val) {
        if (val) this.getSubList()
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    meta () {
      const items = this.items || []
      return useMeta(items, this.unit)
    },
    isFree () {
      return !this.cost || !this.cost.length
    },
    tenantCode () {
      return this._tenantCode()
    },
    isPurchased () {
      return this.selectBiList.filter(v => v.appId === this.appId).length > 0
    },
    payStateName () {
      return this.getCurrentPayState()
    },
    payBundle () {
      return this.bundleName === 'STARTUP' || this.bundleName === 'PROFESSIONAL'
    }
  },
  filters: {
    filterUnitCode (val) {
      return capitalize(val)
    }
  },
  async mounted () {
    this.getBiPackageList()
  },
  methods: {
    purchase () {
      if (this.payStateName === 'Upgrade') {
        this.$emit('close')
        this.$root.eventBus.$emit('marketPlaceTabClick', { name: 'bundle' })
      } else {
        this.$emit('purchase')
      }
    },

    async install () {
      const params = {
        appId: this.appId,
        all: false,
        tenantList: null
      }
      const { postAddToMyAppsApi } = this.$interface.reports
      const { data: response } = await postAddToMyAppsApi(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data
    },
    add () {
      this.$confirm(this.$t('custom.apps.add'), this.$t('custom.apps.warning'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        dangerouslyUseHTMLString: true,
        callback: () => { },
        beforeClose: async (action, ctx, close) => {
          if (action !== 'confirm') {
            return close()
          }
          try {
            ctx.confirmButtonLoading = true
            await this.install()
            close()
            this.$emit('close')
          } finally {
            ctx.confirmButtonLoading = false
          }
        }
      }).then(() => {

      }).catch(() => {
      })
    },
    async getSubList () {
      const { subList } = this.$interface.pay
      const tenantCode = this.tenantCode || this.$store.state.user.tenantCode
      const { data } = await subList({ tenantCode })
      if (data.data && data.data.length) {
        this.payHistory = data.data
        const _f = this.payHistory.filter(v => v.appId === this.appId && v.payStatus)
        this.isPay = _f.length > 0
        const bundle = data.data.filter(v => v.type === 0 && v.payStatus)
        if (bundle.length) this.bundleName = bundle[0].name
      }
    },
    async getBiPackageList () {
      const { getBiPackageList } = this.$interface.pay
      const { data } = await getBiPackageList({ tenantCode: this.$store.state.user.tenantCode })
      this.selectBiList = data
    },
    getCurrentPayState () {
      if (this.bundleName === 'STARTUP') {
        if (this.type === 1) {
          return this.payBundle ? this.$t('paywall.purchased') : (this.isPay ? this.$t('paywall.purchased') : this.$t('paywall.purchase'))
        } else if (this.type === 2) {
          return this.isPurchased ? this.$t('paywall.purchased') : ((this.installed && (this.isPay || this.isPurchased)) ? this.$t('paywall.purchased') : this.$t('paywall.upgrade'))
        } else if (this.type === 3) {
          return this.aliseName === 'Bot Usage' ? this.$t('paywall.purchased') : this.$t('paywall.upgrade')
        }
      } else if (this.bundleName === 'PROFESSIONAL') {
        return this.$t('paywall.purchased')
      } else {
        if (this.type === 1 || this.type === 3) {
          return this.$t('paywall.purchase')
        } else {
          return (this.installed && (this.isPay || this.isPurchased)) ? this.$t('paywall.purchased') : this.$t('paywall.purchase')
        }
      }
    },
    getDisabledState () {
      if (this.bundleName === 'PROFESSIONAL') return true

      if (this.type === 2) {
        return this.payBundle && this.isPurchased
      } else if (this.type === 3) {
        return this.payStateName !== 'Upgrade' && this.payStateName !== 'Purchase'
      } else if (this.type === 1) {
        return this.payBundle
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.b-dialog-application__side-pay-price {
  flex-direction: row !important;
}
.b-dialog-application__side {
  width: 220px;
  padding-right: 16px;
  min-height: 588px;
  &-item {
    margin-bottom: 13px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    &--name {
      font-size: 14px;
      color: #8d8d8d;
    }
    &--value {
      font-size: 14px;
      color: #161616;
    }

    &-price {
      display: inline-flex;
      flex-direction: column;
      &--unit {
        text-align: right;
        font-size: 14px;
        color: #8d8d8d;
      }
    }
  }
  &-pay {
    flex: 1;
    display: flex;
    flex-direction: column;
    box-shadow: inset 0px 1px 0px 0px #f0f0f0;
    padding-top: 16px;
    //justify-content: space-between;
  }
}
</style>

<style lang="scss">
.price-tooltip {
  width: 200px;
}
</style>
